﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using ReAnimation.Helpers.Common;

namespace ReAnimation.Controls
{
    public partial class NumericTextField : UserControl
    {
        public event EventHandler ValueChanged;

        public TextBox InnerTextBox
        {
            get
            {
                return textBox1;
            }
        }

        public float Value
        {
            get
            {
                if (String.IsNullOrEmpty(textBox1.Text)) return 0;
                return float.Parse(textBox1.Text);
            }
            set
            {
                textBox1.Text = value.ToString().Replace(",", ".");
            }
        }

        public NumericTextField()
        {
            InitializeComponent();
        }

        private void textBox1_Validating(object sender, CancelEventArgs e)
        {
            if (String.IsNullOrEmpty(textBox1.Text)) return;
            Regex r = new Regex("^-?([0-9]+.?)?[0-9]*$");
            e.Cancel =  ! r.Match(textBox1.Text).Success;
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (!((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9) || e.KeyCode == Keys.OemMinus
                || e.KeyCode == Keys.Back || e.KeyCode == Keys.OemPeriod))
            {
                
                e.SuppressKeyPress = true;
            }
        }

        private void textBox1_Validated(object sender, EventArgs e)
        {
            
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            Regex r = new Regex("^-?([0-9]+.?)?[0-9]*$");
            if (r.Match(textBox1.Text).Success) return;
            if (textBox1.Text.Length > 0)
            {
                textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1, 1);
                textBox1.SelectionStart = textBox1.Text.Length;
            }
            ValueChanged.Throw(this, e);
        }

        private void textBox1_Enter(object sender, EventArgs e)
        {
            textBox1.SelectionStart = textBox1.Text.Length;
        }

        private void textBox1_Click(object sender, EventArgs e)
        {
            textBox1.SelectionStart = textBox1.Text.Length;
        }
    }
}
